<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>Java异常处理机制 - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="Java异常处理机制"><meta property="og:title" content="Java异常处理机制" />
<meta property="og:description" content="Java异常处理机制" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-01-23T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-01-23T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="Java异常处理机制"/>
<meta name="twitter:description" content="Java异常处理机制"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" /><link rel="prev" href="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" /><link rel="next" href="https://acking-you.github.io/posts/java%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Java异常处理机制",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/java%E5%BC%82%E5%B8%B8\/"
        },"genre": "posts","keywords": "Java异常处理","wordcount":  2943 ,
        "url": "https:\/\/acking-you.github.io\/posts\/java%E5%BC%82%E5%B8%B8\/","datePublished": "2022-01-23T00:00:00+00:00","dateModified": "2022-01-23T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "Java异常处理机制"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/c3d009d6542a44155b5847c3a9c76dcd.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/c3d009d6542a44155b5847c3a9c76dcd.png#pic_center, https://img-blog.csdnimg.cn/img_convert/c3d009d6542a44155b5847c3a9c76dcd.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/c3d009d6542a44155b5847c3a9c76dcd.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/c3d009d6542a44155b5847c3a9c76dcd.png#pic_center"
        title="Java异常处理机制" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">Java异常处理机制</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/javase%E7%AC%94%E8%AE%B0/"><i class="far fa-folder fa-fw"></i>JavaSE笔记</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-01-23">2022-01-23</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 2943 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 6 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#异常">异常</a>
      <ul>
        <li><a href="#运行时异常">运行时异常</a></li>
        <li><a href="#编译时异常">编译时异常</a></li>
      </ul>
    </li>
    <li><a href="#错误">错误</a></li>
    <li><a href="#异常的处理">异常的处理</a></li>
    <li><a href="#异常的抛出">异常的抛出</a></li>
    <li><a href="#自定义异常">自定义异常</a></li>
    <li><a href="#多重异常捕获和finally关键字">多重异常捕获和finally关键字</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h1 id="java异常机制">Java异常机制</h1>
<p><a href="https://www.bilibili.com/video/BV1Gv411T7pi?p=46" target="_blank" rel="noopener noreffer">配套视频</a></p>
<p>在理想的情况下，我们的程序会按照我们的思路去运行，按理说是不会出现问题的，但是，代码实际编写后并不一定是完美的，可能会有我们没有考虑到的情况，如果这些情况能够正常得到一个错误的结果还好，但是如果直接导致程序运行出现问题了呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">test</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="n">0</span><span class="o">);</span>   <span class="c1">//当b为0的时候，还能正常运行吗？
</span><span class="c1"></span><span class="o">}</span>

<span class="kd">private</span> <span class="kd">static</span> <span class="kt">int</span> <span class="nf">test</span><span class="o">(</span><span class="kt">int</span> <span class="n">a</span><span class="o">,</span> <span class="kt">int</span> <span class="n">b</span><span class="o">){</span>
    <span class="k">return</span> <span class="n">a</span><span class="o">/</span><span class="n">b</span><span class="o">;</span>   <span class="c1">//没有任何的判断而是直接做计算
</span><span class="c1"></span><span class="o">}</span>

<span class="n">Exception</span> <span class="n">in</span> <span class="n">thread</span> <span class="s">&#34;main&#34;</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">ArithmeticException</span><span class="o">:</span> <span class="o">/</span> <span class="n">by</span> <span class="n">zero</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Application</span><span class="o">.</span><span class="na">test</span><span class="o">(</span><span class="n">Application</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">9</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Application</span><span class="o">.</span><span class="na">main</span><span class="o">(</span><span class="n">Application</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">5</span><span class="o">)</span>
</code></pre></div><p>当程序运行出现我们没有考虑到的情况时，就有可能出现异常或是错误！</p>
<h2 id="异常">异常</h2>
<p>我们在之前其实已经接触过一些异常了，比如数组越界异常，空指针异常，算术异常等，他们其实都是异常类型，我们的每一个异常也是一个类，他们都继承自<code>Exception</code>类！异常类型本质依然类的对象，但是异常类型支持在程序运行出现问题时抛出（也就是上面出现的红色报错）也可以提前声明，告知使用者需要处理可能会出现的异常！</p>
<h3 id="运行时异常">运行时异常</h3>
<p>异常的第一种类型是运行时异常，如上述的列子，在编译阶段无法感知代码是否会出现问题，只有在运行的时候才知道会不会出错（正常情况下是不会出错的），这样的异常称为运行时异常。所有的运行时异常都继承自<code>RuntimeException</code>。</p>
<h3 id="编译时异常">编译时异常</h3>
<p>异常的另一种类型是编译时异常，编译时异常是明确会出现的异常，在编译阶段就需要进行处理的异常（捕获异常）如果不进行处理，将无法通过编译！默认继承自<code>Exception</code>类的异常都是编译时异常。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">File</span> <span class="n">file</span> <span class="o">=</span> <span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="s">&#34;my.txt&#34;</span><span class="o">);</span>
<span class="n">file</span><span class="o">.</span><span class="na">createNewFile</span><span class="o">();</span>   <span class="c1">//要调用此方法，首先需要处理异常
</span></code></pre></div><h2 id="错误">错误</h2>
<p>错误比异常更严重，异常就是不同寻常，但不一定会导致致命的问题，而错误是致命问题，一般出现错误可能JVM就无法继续正常运行了，比如<code>OutOfMemoryError</code>就是内存溢出错误（内存占用已经超出限制，无法继续申请内存了）</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kt">int</span><span class="o">[]</span> <span class="n">arr</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">int</span><span class="o">[</span><span class="n">Integer</span><span class="o">.</span><span class="na">MAX_VALUE</span><span class="o">];</span>   <span class="c1">//能创建如此之大的数组吗？
</span></code></pre></div><p>运行后得到以下内容：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Exception</span> <span class="n">in</span> <span class="n">thread</span> <span class="s">&#34;main&#34;</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">OutOfMemoryError</span><span class="o">:</span> <span class="n">Requested</span> <span class="n">array</span> <span class="n">size</span> <span class="n">exceeds</span> <span class="n">VM</span> <span class="n">limit</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">main</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">14</span><span class="o">)</span>
</code></pre></div><p>错误都继承自<code>Error</code>类，一般情况下，程序中只能处理异常，错误是很难进行处理的，<code>Error</code>和<code>Execption</code>都继承自<code>Throwable</code>类。当程序中出现错误或异常时又没有进行处理时，程序（当前线程）将终止运行：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kt">int</span><span class="o">[]</span> <span class="n">arr</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">int</span><span class="o">[</span><span class="n">Integer</span><span class="o">.</span><span class="na">MAX_VALUE</span><span class="o">];</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>  <span class="c1">//还能正常打印吗？
</span></code></pre></div><h2 id="异常的处理">异常的处理</h2>
<p>当程序没有按照我们想要的样子运行而出现异常时（默认会交给JVM来处理，JVM发现任何异常都会立即终止程序运行，并在控制台打印栈追踪信息），我们希望能够自己处理出现的问题，让程序继续运行下去，就需要对异常进行捕获，比如：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kt">int</span><span class="o">[]</span> <span class="n">arr</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">int</span><span class="o">[</span><span class="n">5</span><span class="o">];</span>
<span class="n">arr</span><span class="o">[</span><span class="n">5</span><span class="o">]</span> <span class="o">=</span> <span class="n">1</span><span class="o">;</span>  <span class="c1">//我们需要处理这种情况，保证后面的代码正常运行！
</span><span class="c1"></span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>
</code></pre></div><p>我们可以使用<code>try</code>和<code>catch</code>语句块来处理：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kt">int</span><span class="o">[]</span> <span class="n">arr</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">int</span><span class="o">[</span><span class="n">5</span><span class="o">];</span>
<span class="k">try</span><span class="o">{</span>    <span class="c1">//在try块中运行代码
</span><span class="c1"></span>     <span class="n">arr</span><span class="o">[</span><span class="n">5</span><span class="o">]</span> <span class="o">=</span> <span class="n">1</span><span class="o">;</span>    <span class="c1">//当代码出现异常时，异常会被捕获，并在catch块中得到异常类型的对象
</span><span class="c1"></span><span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">ArrayIndexOutOfBoundsException</span> <span class="n">e</span><span class="o">){</span>   <span class="c1">//捕获的异常类型
</span><span class="c1"></span>     <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;程序运行出现异常！&#34;</span><span class="o">);</span>  <span class="c1">//出现异常时执行
</span><span class="c1"></span><span class="o">}</span>
<span class="c1">//后面的代码会正常运行
</span><span class="c1"></span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>
</code></pre></div><p>当异常被捕获后，就由我们自己进行处理（不再交给JVM处理），因此就不会导致程序终止运行。</p>
<p>我们可以通过使用<code>e.printStackTrace()</code>来打印栈追踪信息，定位我们的异常出现位置：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">ArrayIndexOutOfBoundsException</span><span class="o">:</span> <span class="n">5</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">main</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">7</span><span class="o">)</span>    <span class="c1">//Main类的第7行出现问题
</span><span class="c1"></span><span class="n">程序运行出现异常</span><span class="err">！</span>
<span class="n">lbwnb</span>
</code></pre></div><p>运行时异常在编译时可以不用捕获，但是编译时异常必须进行处理：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">File</span> <span class="n">file</span> <span class="o">=</span> <span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="s">&#34;my.txt&#34;</span><span class="o">);</span>
<span class="k">try</span> <span class="o">{</span>
  <span class="n">file</span><span class="o">.</span><span class="na">createNewFile</span><span class="o">();</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>  <span class="c1">//捕获声明的异常类型
</span><span class="c1"></span>  <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>可以捕获到类型不止是<code>Exception</code>的子类，只要是继承自<code>Throwalbe</code>的类，都能被捕获，也就是说，<code>Error</code>也能被捕获，但是不建议这样做，因为错误一般是虚拟机相关的问题，出现<code>Error</code>应该从问题的根源去解决。</p>
<h2 id="异常的抛出">异常的抛出</h2>
<p>当别人调用我们的方法时，如果传入了错误的参数导致程序无法正常运行，这时我们就需要手动抛出一个异常来终止程序继续运行下去，同时告知上一级方法执行出现了问题：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">test</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="n">0</span><span class="o">);</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>   <span class="c1">//捕获方法中会出现的异常
</span><span class="c1"></span>            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kd">static</span> <span class="kt">int</span> <span class="nf">test</span><span class="o">(</span><span class="kt">int</span> <span class="n">a</span><span class="o">,</span> <span class="kt">int</span> <span class="n">b</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>  <span class="c1">//声明抛出的异常类型
</span><span class="c1"></span>        <span class="k">if</span><span class="o">(</span><span class="n">b</span> <span class="o">==</span> <span class="n">0</span><span class="o">)</span> <span class="k">throw</span> <span class="k">new</span> <span class="n">Exception</span><span class="o">(</span><span class="s">&#34;0不能做除数！&#34;</span><span class="o">);</span>  <span class="c1">//创建异常对象并抛出异常
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">a</span><span class="o">/</span><span class="n">b</span><span class="o">;</span>  <span class="c1">//抛出异常会终止代码运行
</span><span class="c1"></span>    <span class="o">}</span>
</code></pre></div><p>通过<code>throw</code>关键字抛出异常（抛出异常后，后面的代码不再执行）当程序运行到这一行时，就会终止执行，并出现一个异常。</p>
<p>如果方法中抛出了非运行时异常，但是不希望在此方法内处理，而是交给调用者来处理异常，就需要在方法定义后面显式声明抛出的异常类型！如果抛出的是运行时异常，则不需要在方法后面声明异常类型，调用时也无需捕获，但是出现异常时同样会导致程序终止（出现运行时异常同时未被捕获会默认交给JVM处理，也就是直接中止程序并在控制台打印栈追踪信息）</p>
<p>如果想要调用声明编译时异常的方法，但是依然不想去处理，可以同样的在方法上声明<code>throws</code>来继续交给上一级处理。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>  <span class="c1">//出现异常就再往上抛，而不是在此方法内处理
</span><span class="c1"></span>  <span class="n">test</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="n">0</span><span class="o">);</span>
<span class="o">}</span>

<span class="kd">private</span> <span class="kd">static</span> <span class="kt">int</span> <span class="nf">test</span><span class="o">(</span><span class="kt">int</span> <span class="n">a</span><span class="o">,</span> <span class="kt">int</span> <span class="n">b</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>  <span class="c1">//声明抛出的异常类型
</span><span class="c1"></span>  <span class="k">if</span><span class="o">(</span><span class="n">b</span> <span class="o">==</span> <span class="n">0</span><span class="o">)</span> <span class="k">throw</span> <span class="k">new</span> <span class="n">Exception</span><span class="o">(</span><span class="s">&#34;0不能做除数！&#34;</span><span class="o">);</span>  <span class="c1">//创建异常对象并抛出异常      
</span><span class="c1"></span>  <span class="k">return</span> <span class="n">a</span><span class="o">/</span><span class="n">b</span><span class="o">;</span>  
<span class="o">}</span>
</code></pre></div><p>当main方法都声明抛出异常时，出现异常就由JVM进行处理，也就是默认的处理方式（直接中止程序并在控制台打印栈追踪信息）</p>
<p>异常只能被捕获一次，当异常捕获出现嵌套时，只会在最内层被捕获：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
        <span class="k">try</span><span class="o">{</span>
            <span class="n">test</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="n">0</span><span class="o">);</span>
        <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">){</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;外层&#34;</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kd">static</span> <span class="kt">int</span> <span class="nf">test</span><span class="o">(</span><span class="kt">int</span> <span class="n">a</span><span class="o">,</span> <span class="kt">int</span> <span class="n">b</span><span class="o">){</span>
        <span class="k">try</span><span class="o">{</span>
            <span class="k">if</span><span class="o">(</span><span class="n">b</span> <span class="o">==</span> <span class="n">0</span><span class="o">)</span> <span class="k">throw</span> <span class="k">new</span> <span class="n">Exception</span><span class="o">(</span><span class="s">&#34;0不能做除数！&#34;</span><span class="o">);</span>
        <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">){</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;内层&#34;</span><span class="o">);</span>
            <span class="k">return</span> <span class="n">0</span><span class="o">;</span>
        <span class="o">}</span>
        <span class="k">return</span> <span class="n">a</span><span class="o">/</span><span class="n">b</span><span class="o">;</span>
    <span class="o">}</span>
</code></pre></div><h2 id="自定义异常">自定义异常</h2>
<p>JDK为我们已经提前定义了一些异常了，但是可能对我们来说不够，那么就需要自定义异常：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyException</span> <span class="kd">extends</span> <span class="n">Exception</span> <span class="o">{</span>  <span class="c1">//直接继承即可
</span><span class="c1"></span>    
<span class="o">}</span>

<span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">MyException</span> <span class="o">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="n">MyException</span><span class="o">();</span>   <span class="c1">//直接使用
</span><span class="c1"></span>    <span class="o">}</span>
</code></pre></div><p>也可以使用父类的带描述的构造方法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyException</span> <span class="kd">extends</span> <span class="n">Exception</span> <span class="o">{</span>

    <span class="kd">public</span> <span class="nf">MyException</span><span class="o">(</span><span class="n">String</span> <span class="n">message</span><span class="o">){</span>
        <span class="kd">super</span><span class="o">(</span><span class="n">message</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">MyException</span> <span class="o">{</span>
    <span class="k">throw</span> <span class="k">new</span> <span class="n">MyException</span><span class="o">(</span><span class="s">&#34;出现了自定义的错误&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>捕获异常指定的类型，会捕获其所有子异常类型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">{</span>
  <span class="k">throw</span> <span class="k">new</span> <span class="n">MyException</span><span class="o">(</span><span class="s">&#34;出现了自定义的错误&#34;</span><span class="o">);</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>    <span class="c1">//捕获父异常类型
</span><span class="c1"></span>  <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;捕获到异常&#34;</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><h2 id="多重异常捕获和finally关键字">多重异常捕获和finally关键字</h2>
<p>当代码可能出现多种类型的异常时，我们希望能够分不同情况处理不同类型的异常，就可以使用多重异常捕获：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">{</span>
  <span class="c1">//....
</span><span class="c1"></span><span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">NullPointerException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IndexOutOfBoundsException</span> <span class="n">e</span><span class="o">){</span>

<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">RuntimeException</span> <span class="n">e</span><span class="o">){</span>
            
<span class="o">}</span>
</code></pre></div><p>注意，类似于<code>if-else if</code>的结构，父异常类型只能放在最后！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">{</span>
  <span class="c1">//....
</span><span class="c1"></span><span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">RuntimeException</span> <span class="n">e</span><span class="o">){</span>  <span class="c1">//父类型在前，会将子类的也捕获
</span><span class="c1"></span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">NullPointerException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>   <span class="c1">//永远都不会被捕获
</span><span class="c1"></span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IndexOutOfBoundsException</span> <span class="n">e</span><span class="o">){</span>   <span class="c1">//永远都不会被捕获
</span><span class="c1"></span>
<span class="o">}</span>
</code></pre></div><p>如果希望把这些异常放在一起进行处理：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">{</span>
     <span class="c1">//....
</span><span class="c1"></span><span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">NullPointerException</span> <span class="o">|</span> <span class="n">IndexOutOfBoundsException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>  <span class="c1">//用|隔开每种类型即可
</span><span class="c1"></span>
<span class="o">}</span>
</code></pre></div><p>当我们希望，程序运行时，无论是否出现异常，都会在最后执行的任务，可以交给<code>finally</code>语句块来处理：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">{</span>
    <span class="c1">//....
</span><span class="c1"></span><span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">){</span>
            
<span class="o">}</span><span class="k">finally</span> <span class="o">{</span>
  <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>   <span class="c1">//无论是否出现异常，都会在最后执行
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p><code>try</code>语句块至少要配合<code>catch</code>或<code>finally</code>中的一个：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="k">try</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="n">10</span><span class="o">;</span>
    <span class="n">a</span> <span class="o">/=</span> <span class="n">0</span><span class="o">;</span>
<span class="o">}</span><span class="k">finally</span> <span class="o">{</span>  <span class="c1">//不捕获异常，程序会终止，但在最后依然会执行下面的内容
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">);</span> 
<span class="o">}</span>
</code></pre></div><p>思考：<code>try</code>、<code>catch</code>和<code>finally</code>执行顺序：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">private</span> <span class="kd">static</span> <span class="kt">int</span> <span class="nf">test</span><span class="o">(</span><span class="kt">int</span> <span class="n">a</span><span class="o">){</span>
  <span class="k">try</span><span class="o">{</span>
    <span class="k">return</span> <span class="n">a</span><span class="o">;</span>
  <span class="o">}</span><span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">){</span>
    <span class="k">return</span> <span class="n">0</span><span class="o">;</span>
  <span class="o">}</span><span class="k">finally</span> <span class="o">{</span>
    <span class="n">a</span> <span class="o">=</span>  <span class="n">a</span> <span class="o">+</span> <span class="n">1</span><span class="o">;</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/java%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/">Java异常处理</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-01-23</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-title="Java异常处理机制" data-hashtags="Java异常处理"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-hashtag="Java异常处理"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-title="Java异常处理机制" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-title="Java异常处理机制"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-title="Java异常处理机制" data-image="https://img-blog.csdnimg.cn/img_convert/c3d009d6542a44155b5847c3a9c76dcd.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-title="Java异常处理机制" data-description="Java异常处理机制"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-title="Java异常处理机制" data-description="Java异常处理机制"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" data-title="Java异常处理机制"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" class="prev" rel="prev" title="Java泛型与集合类"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/java%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1/" class="next" rel="next" title="Java对象和多态">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
